﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.KDThread;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using RestSharp;
using RK.Model.Ronma;
using RK.Tools;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RK.ListBillPlugin.Ronma
{
    [Description("Ronma:手动同步备品备件安灯消息"), HotUpdate]
    public class ListAnDeng : AbstractListPlugIn
    {
        public override void BarItemClick(BarItemClickEventArgs e)
        {
            base.BarItemClick(e);
            //手动同步OA状态
            if (e.BarItemKey.EqualsIgnoreCase("tb_AnDeng"))
            {
                ShowProgressBar(true);
            }
        }

        private void ShowProgressBar(bool userTruePro)
        {
            this.View.ShowProcessForm(formResult => { }, userTruePro, "正在执行安灯消息同步...");
            MainWorker.QuequeTask(this.View.Context, () =>
            {
                try
                {
                    DynamicObjectCollection matList = GetMatList(this.Context);
                    var counter = matList.Count;
                    for (int i = 1; i < counter; i++)
                    {
                        // TODO
                        if (matList.Count > 0)
                        {
                            DynamicObjectCollection tuiSongRen = KingdeeTools.GetTuiSongRen(this.Context);
                            foreach (var song in tuiSongRen)
                            {
                                int groupId = Convert.ToInt32(song["FGROUP"]);
                                string tsr = Convert.ToString(song["FNAME"]);
                                var s1 = matList.Where(s => Convert.ToInt32(s["FGROUP"]) == groupId).ToList();
                                if (s1.Count > 0)
                                {
                                    List<string> list = new List<string>();
                                    list.Clear();
                                    list.Add($"备品备件安灯消息：{DateTime.Now.ToString()}\r\n");
                                    foreach (var s2 in s1)
                                    {
                                        list.Add($"物料代码:{s2["FNUMBER"].ToString()},物料名称:{s2["FNAME"].ToString()},安全库存:{s2["FSAFESTOCK"].ToString()},实际库存:{s2["FBASEQTY"].ToString()};\r\n");
                                    }
                                    SyncAnDeng(tsr, list);
                                }
                            }
                            DynamicObjectCollection zongTs = GetZongTs(this.Context);
                            foreach (var zts in zongTs)
                            {
                                int groupId = Convert.ToInt32(zts["FGROUP"]);
                                string tsr = Convert.ToString(zts["FNAME"]);
                                var s1 = matList.Where(s => Convert.ToInt32(s["FGROUP"]) == groupId).ToList();
                                if (s1.Count > 0)
                                {
                                    List<string> list = new List<string>();
                                    list.Clear();
                                    list.Add($"备品备件安灯消息：{DateTime.Now.ToString()}\r\n");
                                    foreach (var s2 in s1)
                                    {
                                        list.Add($"物料代码:{s2["FNUMBER"].ToString()},物料名称:{s2["FNAME"].ToString()},安全库存:{s2["FSAFESTOCK"].ToString()},实际库存:{s2["FBASEQTY"].ToString()};\r\n");
                                    }
                                    SyncAnDeng(tsr, list);
                                }
                            }
                        }
                        Thread.Sleep(1000);
                        // 报告下执行进度
                        var rate = Convert.ToInt32(i * 100 / counter);
                        this.View.Session["ProcessRateValue"] = rate;
                        // 进度条界面增加文字提示信息
                        this.View.Session["ProcessTips"] = string.Format("任务{0}已处理", i);
                    }
                    this.View.ShowMessage("操作已完成。");
                }
                catch (Exception ex)
                {
                    this.View.ShowErrMessage(ex.Message);
                }
                finally
                {
                    // 此句必不可少，进度值100时进度条自动关闭
                    this.View.Session["ProcessRateValue"] = 100;
                    this.View.SendDynamicFormAction(this.View);
                }
            }, null);
        }

        private DynamicObjectCollection GetZongTs(Context context)
        {
            string sql = string.Format(@"/*dialect*/ 
            SELECT T0.FGROUP, 
                   T2.FNAME
            FROM YCVN_t_Cust_Entry100018 T0
                 JOIN YCVN_t_Cust_0002 T1 ON T1.FEntryID = T0.FEntryID
                 JOIN T_HR_EMPINFO_L T2 ON T2.FID = T1.F_YG_ZTS
                               AND T2.FLOCALEID = 2052 ");
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(context, sql);
            return doc;
        }

        private void SyncAnDeng(string tsr, List<string> list)
        {
            string str = string.Join(",", list);
            AnDengModel anDengModel = new AnDengModel();
            anDengModel.msgtype = "sampleText";
            anDengModel.ocid = "51992318-03a6-4154-9e86-2c3045fde73b";
            anDengModel.msg = str;
            anDengModel.atusers = tsr;
            var client = new RestClient("http://10.10.11.150:8000/Ding/Json/");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            client.UserAgent = "apifox/1.0.0 (https://www.apifox.cn)";
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "*/*");
            request.AddHeader("Host", "10.10.11.150:8000");
            request.AddHeader("Connection", "keep-alive");
            var body = JsonConvert.SerializeObject(anDengModel);
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
        }

        private DynamicObjectCollection GetMatList(Context context)
        {
            string sql = string.Format(@"/*dialect*/ 
            SELECT T2.FID FGROUP, 
                   T2.FNUMBER FGROUPNUMBER, 
                   T1.FNUMBER, 
                   T4.FNAME, 
                   MAX(T3.FSAFESTOCK) FSAFESTOCK, 
                   SUM(T0.FBASEQTY) FBASEQTY
            FROM T_STK_INVENTORY T0
                 JOIN T_BD_MATERIAL T1 ON T1.FMATERIALID = T0.FMATERIALID
                 JOIN T_BD_MATERIALGROUP T2 ON T2.FID = T1.FMATERIALGROUP
                 JOIN t_BD_MaterialStock T3 ON T3.FMATERIALID = T1.FMATERIALID
                 JOIN T_BD_MATERIAL_L T4 ON T4.FMATERIALID = T1.FMATERIALID
                                            AND T4.FLOCALEID = 2052
            WHERE T1.FMATERIALGROUP IN
            (
                SELECT DISTINCT 
                       FGROUP
                FROM YCVN_t_Cust_Entry100018
            )
            GROUP BY T0.FSTOCKORGID, 
                     T2.FID, 
                     T1.FNUMBER, 
                     T2.FNUMBER, 
                     T4.FNAME
            HAVING SUM(T0.FBASEQTY) < MAX(T3.FSAFESTOCK) ");
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            return doc;
        }
    }
}
